package com.nbicc.dp.modular.exception;

import com.nbicc.core.common.ResponseUtil;
import com.nbicc.core.utils.ExceptionUtil;
import com.nbicc.dp.modular.exception.custom.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by li on 17/12/22.
 * 在controller里执行逻辑代码时出的异常。譬如NullPointerException。
 */
@Slf4j
@ControllerAdvice
public class RunningExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = CustomException.class)
    @ResponseBody
    public ResponseEntity<ModelMap> DuplicateKeyExceptionHandler(HttpServletRequest request, HttpServletResponse response , CustomException e)
            throws Exception {
        ResponseEntity<ModelMap> responseEntity = ResponseUtil.setModelMap(e.getStatus(), null, e.getMessage());
        response.setStatus(e.getStatus().value());
        log.error(responseEntity.toString());
        return responseEntity;
    }

    @ExceptionHandler(value = DuplicateKeyException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseEntity<ModelMap> DuplicateKeyExceptionHandler(HttpServletRequest request, HttpServletResponse response , Exception e)
            throws Exception {
        ResponseEntity<ModelMap> responseEntity = ResponseUtil.setModelMap(HttpStatus.INTERNAL_SERVER_ERROR, null, "不允许重复插入");
        log.error(responseEntity.toString());
        return responseEntity;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseEntity<ModelMap> ExceptionHandler(HttpServletRequest request, HttpServletResponse response , Exception e)
            throws Exception {
        ResponseEntity<ModelMap> responseEntity = ResponseUtil.setModelMap(HttpStatus.INTERNAL_SERVER_ERROR, null , e.getMessage());
        log.error(responseEntity.toString());
        return responseEntity;
    }


}
